package Randomwriting;
import java.util.Vector;
import structure5.*;

public class Table {
	public Vector<Association> charSeq = new Vector<Association>();//field property
	/**
	 * 
	 * @param word character sequence (stored as a String) as its key of the Association
	 * @param c the character after the keyWord
	 */
	public void updateProbabilities(String word, String c)
	{
		Association wordInfo;
		String existingWord;
		int i;
		for (i = 0; i < charSeq.size(); i++)
		{
			// get the association
			wordInfo = (Association)charSeq.get(i);
			// get the word from the association
			existingWord = (String)wordInfo.getKey();
			
			if (existingWord.equals(word))
			{ 
				// match: increment integer in association
				FreqList fl = (FreqList) wordInfo.getValue();
				fl.updateCount(c);
				break;
			}
		}
		// mismatch: add new word, frequency 1.
		if (i == charSeq.size())
		{
			charSeq.add(new Association(word,new FreqList(c)));
		}
	}
	
	public String generateRandomText(String word, int length)
	{
		String randomText=word;
		//int initLength=word.length()-1;
		for(int i=0; i<length-word.length();i++)
		{
			randomText=randomText+selectNextChar(randomText.substring(i));
		}
		
		return randomText;
	}
	
	public String selectNextChar(String word)
	{
		String nextChar="";
		
		Association wordInfo;
		FreqList fl;
		for(int i=0; i<charSeq.size(); i++)
		{
			wordInfo = (Association)charSeq.get(i);
			if( word.equals((String)wordInfo.getKey()) )
			{
				//System.out.println(word);
				fl = (FreqList) wordInfo.getValue();
				nextChar=fl.getHighestFreqChar();
			}
		}
		
		if(nextChar.length()==0)
		{
			int rand=(int) (Math.random() * charSeq.size());
			wordInfo = (Association)charSeq.get(rand);
			fl = (FreqList) wordInfo.getValue();
			nextChar=fl.getHighestFreqChar();
		}
		
		return nextChar;
	}
	
	public String pickARandomWord()
	{
		String randomWord="";
		Association wordInfo;
		int rand=(int) (Math.random() * charSeq.size());
		wordInfo = (Association)charSeq.get(rand);
		randomWord = (String)wordInfo.getKey();
		return randomWord;
	}
	
	public void printTable()
	{
		Association wordInfo;
		String word;
		FreqList fl;
		for (int i = 0; i < charSeq.size(); i++)
		{
			wordInfo = (Association)charSeq.get(i);
			word  = (String) wordInfo.getKey();
			System.out.println(word+"***"+selectNextChar(word));
			fl = (FreqList) wordInfo.getValue();
			fl.printFrequencies();
		}
	}
	
}
